package cn.czxy.utils;


import cn.czxy.domain.File_Type;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangyuan@163.com
 * @date 2019/4/12
 * @infos
 */
public class FileDataUtils2 {

    private static String xPath;

    public FileDataUtils2(String xPath) {
        this.xPath = xPath;
    }

    //图片文件地址
    private  static  String imgFilePath;
    //视频文件地址
    private  static  String videoFilePath;
    //文本文件地址
    private  static  String textFilePath;
    //音频文件地址
    private  static  String musicFilePath;
    //其他类型
    private  static  String otherFilePath;


    //这是  扩展名集合 和  对应的类型的实体类
    private  static  List<File_Type> file_types = new ArrayList<File_Type>();


    //图片文件夹名
    private static final String imgFileName="/imges/";
    //音频文件夹名
    private static final String musicFileName="/music/";
    //文本文件夹名
    private static final String textFileName="/texts/";
    //视频文件夹名
    private static final String videoFileName="/videos/";
    //其他文件夹名
    private static final String otherFileName="/other/";



    /**
     *
     * @param childPath 该参数是指定 files 下的 /用户文件
     */
    private static void setPath(String childPath){
        imgFilePath = xPath+childPath+imgFileName;
        videoFilePath = xPath+childPath+videoFileName;
        textFilePath = xPath+childPath+textFileName;
        musicFilePath = xPath+childPath+musicFileName;
        otherFilePath = xPath+childPath+otherFileName;

    }

    //配置不同类型的文件的 对应的后缀名
    static{
        //设置图片
        List<String> imgFileList = new ArrayList<>();
        imgFileList.add("jpg");
        imgFileList.add("png");
        imgFileList.add("JPEG");
        imgFileList.add("GIF");
        imgFileList.add("BMP");
        imgFileList.add("PCX");
        File_Type imgfiletype = new File_Type(imgFileList,"imges");


        //设置视频文件
        List<String> videoFileList = new ArrayList<>();
        videoFileList.add("RMVB");
        videoFileList.add("AVI");
        videoFileList.add("MPEG");
        videoFileList.add("WMV");
        videoFileList.add("mp4");
        File_Type videofiletype = new File_Type(videoFileList,"video");


        //设置文本文件
        List<String> txtFileList = new ArrayList<>();
        txtFileList.add("txt");
        txtFileList.add("html");
        txtFileList.add("htm");
        txtFileList.add("asp");
        txtFileList.add("bat");
        txtFileList.add("c");
        txtFileList.add("css");
        txtFileList.add("js");
        File_Type txtfiletype = new File_Type(txtFileList,"txt");

        //设置音乐文件
        List<String> musicFileList = new ArrayList<>();
        musicFileList.add("CD");
        musicFileList.add("OGG");
        musicFileList.add("MP3");
        musicFileList.add("WMP3PRO");
        File_Type musicfiletype = new File_Type(musicFileList,"music");


        file_types.add(imgfiletype);
        file_types.add(videofiletype);
        file_types.add(txtfiletype);
        file_types.add(musicfiletype);

    }


    /**
     * 文件存储
     * @param userName 用户名
     * @return true添加成功   false添加失败
     */
    public  boolean addFile(String  userName, HttpServletRequest request, HttpServletResponse response)
    {
       /* String header = request.getHeader("content-length");
        if (header==null)
        {
            return false;
        }
        Long head;
        try {
             head = Long.parseLong(header);
        }catch (Exception e)
        {
            return false;
        }
        if (head>1024*1024*25)
        {
            return false;
        }*/


        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();


        ServletFileUpload upload = new ServletFileUpload(factory);


        // 中文处理
        upload.setHeaderEncoding("UTF-8");
        try {
            // 解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String[] split = fileName.split("\\.");
                        setPath(userName);
                        String filePath = null;
                        //判断该文件的类型
                        boolean flag =false;
                        for (File_Type file_type : file_types) {
                            for (String type : file_type.getExtensions()) {
                                if (split[split.length-1].equalsIgnoreCase(type))
                                {
                                    if (file_type.getType().equals("imges"))
                                    {
                                        filePath = imgFilePath+fileName;
                                        flag = true;
                                        break;
                                    }else if (file_type.getType().equals("video"))
                                    {
                                        filePath = videoFilePath+fileName;
                                        flag = true;
                                        break;
                                    }else if (file_type.getType().equals("txt"))
                                    {
                                        filePath = textFilePath+fileName;
                                        flag = true;
                                        break;
                                    }else if (file_type.getType().equals("music"))
                                    {
                                        filePath = musicFilePath+fileName;
                                        flag = true;
                                        break;
                                    }
                                }
                            }
                            if (flag)
                            {
                                break;
                            }
                        }
                        if (flag==false)
                        {
                            filePath = otherFilePath+fileName;
                        }
                        File storeFile = new File(filePath);
                        // 在控制台输出文件的上传路径
                        System.out.println(filePath);
                        // 保存文件到硬盘
                        item.write(storeFile);
                        return true;

                    }
                }
            }
        } catch (Exception ex) {
            ex.getMessage();
            System.out.println(ex.getMessage());
            return false;

        }

        return false;

    }




    /**
     * 文件下载
     * @param FilePath 传入文件的绝对路径值
     * @return false 下载失败  true 下载成功
     */
    public  boolean downLoadFile(String FilePath,HttpServletRequest request,HttpServletResponse response)
    {
        try {
            String path = FilePath; //默认认为文件在当前项目的根目录
            File file = new File(path);
            String name = file.getName();
            FileInputStream fis = new FileInputStream(path);
            response.setCharacterEncoding("utf-8");

            /*
            杨永信添加代码
             */
            /*
            1.2 版
             */
            String header = request.getHeader("User-Agent");
            name = DownLoadUtils.getName(header, name);


            response.setHeader("Content-Disposition", "attachment; filename="+name);
            ServletOutputStream out = response.getOutputStream();
            byte[] bt = new byte[1024];
            int length = 0;
            while((length=fis.read(bt))!=-1){
                out.write(bt,0,length);
            }
            out.close();
            fis.close();
            return true;
        }catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }

    }



}
